<?php
/**
 * 支付回调
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-09
 * Time: 15:33
 */

namespace App\Http\Controllers\Api\V1\Manager\Mall;


use App\Http\Controllers\Controller;
use App\Libs\Contracts\PayMent\AliPay\App\aop\AopCertClient;
use App\Libs\Contracts\PayMent\AliPay\App\aop\AopClient;
use App\Libs\Contracts\PayMent\AliPay\App\aop\request\AlipayFundBatchDetailQueryRequest;
use App\Libs\Contracts\PayMent\AliPay\Web\pagepay\service\AlipayTradeService;
use App\Libs\Contracts\PayMent\Wxpay\WxPayApi;
use App\Libs\httpUtil;
use App\Models\Activity;
use App\Models\ActivityOrder;
use App\Models\ActivityOrderDetail;
use App\Models\BalanceLog;
use App\Models\ContractorCourse;
use App\Models\Course;
use App\Models\CourseOrder;
use App\Models\CourseOrderDetail;
use App\Models\GiftCommodity;
use App\Models\GiftOrder;
use App\Models\GiftOrderDetail;
use App\Models\HealthExamination;
use App\Models\Order;
use App\Models\PaymentCallback;
use App\Models\RechargeOrder;
use App\Models\User;
use App\Models\UserRecharge;
use App\Models\UserWithdrawLog;
use App\Services\Front\AreaTotalService;
use App\Services\Front\CourseService;
use App\Services\Front\QrcodeService;
use App\Services\Front\UserScoreService;
use App\Services\Front\UserService;
use App\Services\Wx\AliService;
use Illuminate\Http\Request;

class NewPayCallbackController extends Controller
{
    /**
     * 支付宝批量打款回调
     * @param Request $request
     */
    public function aliCallback(Request $request)
    {
       // $config = getAliConfig();
        $arr = $_POST;
        \Log::info("支付宝批量打款回调" . json_encode($arr));
        $result = true;
        $body = json_decode($arr['biz_content']);
        if(!isset($body->out_batch_no) && $body->biz_scene == "DIRECT_TRANSFER"){
            UserWithdrawLog::where('orderNo',$body->out_biz_no)->where('auditStatus',"PASS")->update(['accountStatus'=>1,"accountTime"=>date("Y-m-d H:i:s"),"break"=>"打款成功"]);
            echo "success";
            return;
        }
        $batchOrderNo = $body->out_batch_no;//提现批次订单号
        $batch_status = $body->batch_status;//提现批次订单状态
        \Log::info("支付宝批量打款回调参数:" . $batchOrderNo."|||".$batch_status);
        if ($result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            try {
                \DB::beginTransaction();
                if ($batch_status == 'SUCCESS' || $batch_status == 'PART_SUCCESS') {
                    if($batch_status == 'SUCCESS'){
                        UserWithdrawLog::where('batchOrderNo',$batchOrderNo)->where('auditStatus',"PASS")->update(['accountStatus'=>1,"accountTime"=>date("Y-m-d H:i:s"),"break"=>"打款成功"]);
                    }
                    if($batch_status == 'PART_SUCCESS'){
                        $aop = new AopCertClient ();
                        $appCertPath = env("ALI_CERT_PUBLIC_KEY");
                        $alipayCertPath = env("ALI_PAY_CERT_PATH");
                        $rootCertPath = env("ALI_ROOT_CERT_PATH");
                        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                        $aop->appId = env("ALI_APPID");
                        $aop->rsaPrivateKey = env("ALI_PAY_PRIVATE_KEY");
                        $aop->format = 'json';
                        $aop->postCharset = 'UTF-8';
                        $aop->signType = 'RSA2';
                        $aop->apiVersion = '1.0';
                        //调用getPublicKey从支付宝公钥证书中提取公钥
                        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
                        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
                        $aop->isCheckAlipayPublicCert = true;
                        //调用getCertSN获取证书序列号
                        $aop->appCertSN = $aop->getCertSN($appCertPath);
                        //调用getRootCertSN获取支付宝根证书序列号
                        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
                        $request = new AlipayFundBatchDetailQueryRequest();
                        $parmArr = [
                            "biz_scene" => "MESSAGE_BATCH_PAY",
                            "product_code" => "BATCH_API_TO_ACC",
                            "out_batch_no" => "$batchOrderNo"
                        ];
                        $parmArr = json_encode($parmArr);
                        $request->setBizContent($parmArr);
                        $result = $aop->execute($request);
                        $acc_detail_list = $result->alipay_fund_batch_detail_query_response->acc_detail_list;
                        unset($value);
                        foreach ($acc_detail_list as $value){
                            if($value->status == "SUCCESS"){
                                UserWithdrawLog::where('orderNo',$value->out_biz_no)->where('auditStatus',"PASS")->update(['accountStatus'=>1,"accountTime"=>date("Y-m-d H:i:s"),"break"=>"打款成功"]);
                            }else if($value->status == "FAIL"){
                                $userWithdrawLog = UserWithdrawLog::where('orderNo',$value->out_biz_no)->where('auditStatus',"PASS")->lockForUpdate()->first();
                                if($userWithdrawLog){
                                    $userWithdrawLog = $userWithdrawLog->toArray();
                                    $this->returnTheBalance($userWithdrawLog,$value->status,$value->error_msg);
                                }
                            }
                        }
                    }
                }else{
                    if ($batch_status == 'FAIL' || $batch_status == 'DISUSE' || $batch_status == 'INVALID') {
                        $userWithdrawLogList = UserWithdrawLog::where('batchOrderNo',$batchOrderNo)->where('auditStatus',"PASS")->lockForUpdate()->get()->toArray();
                        unset($value);
                        foreach ($userWithdrawLogList as $value){
                            $this->returnTheBalance($value,$batch_status,"全批次GG");
                        }
                    }
                }
                \DB::commit();
                echo "success";
            } catch (\Exception $e) {
                \DB::rollback();
                \Log::error("PayCallbackController aliCallback  " . $e->getMessage());
            }
        } else {
            //验证失败
            echo "fail";    //请不要修改或删除

        }
    }

    function returnTheBalance($userWithdrawLog,$batch_status,$errorDes)
    {
        UserWithdrawLog::where('userWithdrawLogId',$userWithdrawLog['userWithdrawLogId'])->update(['auditStatus'=>"FAIL","errorCode"=>$batch_status,'errorDes'=>$errorDes,"break"=>"打款失败"]);
        $user = User::where('user_id',$userWithdrawLog['user_id'])->lockForUpdate()->first();
        User::where('user_id',$userWithdrawLog['user_id'])->update([
            "income"=> ($user->income + $userWithdrawLog['withdrawPrice']),
            "totalWithdraw"=>($user->totalWithdraw - $userWithdrawLog['withdrawPrice'])
        ]);
    }
}